<?php
namespace app\index\controller;

use think\Request;
use think\Session;
use think\Cookie;

//代理用户
class Member extends Common{
	
	public function index(){
		$response = \ServerHelper::post('wechatlogin',[]);
		$data = $this->J($response);
	}
	
	//个人中心
	public function mine(){
		$param = ['agentid' => AGENT_ID];
		$response = \ServerHelper::post('member_mine',$param);
		$data = $this->J($response);
		if(empty($data['flag'])){
			exit();
		}
		return view('',$data['data']);
	}
	
	//客服微信
	public function kf(){
		return view('');
	}
	
	//解绑微信
	public function unbind_wechat(){
		$req = Request::instance();
		if($req->isPost()){
			$param = ['agentid' => AGENT_ID];
			$response = \ServerHelper::post('^/home/unbindwechat',$param);
			$data = $this->J($response);
			if($data['flag'] == 1){
				Session::clear();
			}
			ajax($data['msg'],$data['flag'] == 1);
		}else{
			return view();
		}
	}
	
	//个人基本信息显示页面
	public function agentinfo(){
		$request = Request::instance();
		$response = \ServerHelper::post('member_agentinfo',['agentid'=>AGENT_ID]);
		$data = $this->J($response);
		return view('',$data['data']);
	}
	
	//执行更换自己的头像
	public function changeheadimage(){
		if(!isset($_FILES["image"]["error"])){
			ajax('请选择图片');
		}
		if($_FILES["image"]["error"] == 1){
			ajax('图片尺寸过大');
		}else if($_FILES["image"]["error"] != 0){
			ajax('图片上传失败');
		}
		$extention = explode('.',$_FILES['image']['name']);
		$extention = end($extention);
		$allow = ['jpg','jpeg','pjpeg','gif','png'];
		if(!in_array(strtolower($extention),$allow)){
			ajax('文件格式不正确');
		}
		$ali = controller('Aliyun');
		$upinfo = $ali->frontupload();
		
		if(empty($upinfo['flag'])){
			ajax('头像上传失败');
		}
		
		$param = [
			'agentid' => AGENT_ID,
			'action' => 'image',
			'value' => $upinfo['data']
		];
		
		$response = \ServerHelper::post('member_agentinfo_save',$param);
		$data = json_decode($response,true);
		if(empty($data['flag'])){
			//优化：删除已上传的OSS图片
			ajax('头像保存失败');
		}else{
			ajax('头像上传成功',true,$upinfo['data']);
		}
	}
	
	//合规金列表
	public function hgj(){
		//^/home/myDeposit.tsl
		$response = \ServerHelper::post('^/home/myDeposit',['agentid'=>AGENT_ID]);
		$data = $this->J($response);
		return view('',$data['data']);
	}
	
	//更改基本的文本资料(我的个人资料更改)
	public function changebaseinfo(){
		$request = Request::instance();
		$action = $request->param('action');
		$param = [
			'agentid' => AGENT_ID,
			'action' => $action , 
			'value' => $request->param('value')
		];
		
		$response = \ServerHelper::post('member_agentinfo_save',$param);
		$data = $this->J($response);
		if(empty($data['flag'])){
			ajax('保存失败');
		}
		ajax('保存成功',true);

	}
		
	//发送手机短信验证码
	public function send_smscode(){
		$request = Request::instance();
		
		$phonenum = $request->param('phonenum');
		$type = $request->param('type','register');
		
		if(!\RegexHelper::is_phone($phonenum)){
			ajax('手机号输入错误');
		}
		
		//拉取SMS配置
		$response = \ServerHelper::post('GetAliyunSMSInfo',['type'=>$type]);
		$data = $this->J($response);
		$smsconfig = $data['data'];
		//短信参数
		$smscode = rand(1000,9999);
		$param = [
			'code' => $smscode,
		];
		//执行发送
		$hp = new \AliyunSMSHelper($smsconfig['accesskeyid'],$smsconfig['accesskeysecret']);
		if($hp->send($phonenum,$smsconfig['sign'],$smsconfig['templete_code'],$param)){
			//记录验证码，5分钟有效
			Cookie::set('smscode_' . $type,$smscode,300);
			ajax('发送成功',true);
		}
		ajax('短信验证码发送失败');
	}
	
	//更换自己的手机号，因为手机号需要验证
	public function changephonenum(){
		$request = Request::instance();
		if($request->isPost()){
			
			$smscode = $request->param('smscode');
			//校验短信码
			$smscode_real = Cookie::get('smscode_resetphonenum');
			if($smscode != $smscode_real){
				ajax('短信码错误');
			}
			
			$param = [
				'agentid' => AGENT_ID,
				'password' => $request->param('password'),//旧密码
				'phonenum' => $request->param('phonenum'),//新手机号
			];
			
			$response = \ServerHelper::post('member_changephonenum',$param);
			$data = $this->J($response);
			if(!isset($data['flag'])){
				ajax('修改失败');
			}
			if($data['flag'] == '0'){
				ajax($data['msg']);
			}
			Cookie::delete('smscode_resetphonenum');
			ajax('修改成功',true);
			
		}else{
			
			$param = ['agentid' => AGENT_ID];
			$response = \ServerHelper::post('member_mine',$param);
			$data = $this->J($response);
			if(empty($data['flag'])){
				abort(404,'数据错误');
				exit();
			}
			
			return view('',$data['data']);
		}
	}
	
	//展示联系总部重置密码页面
	public function resetpassword(){
		$param = ['agentid' => AGENT_ID];
		$response = \ServerHelper::post('member_mine',$param);
		$data = $this->J($response);
		if(empty($data['flag'])){
			abort(404,'数据错误');
			exit();
		}
		return view('',$data['data']);
	}
	
	
	//"我"里面的电子协议列表
	public function protocol(){
		$list = \BaseHelper::GetXieYiList();
		return view('',['list'=>$list]);
	}
	
	//协议内容
	public function protocol_content(){
		$name = Request::instance()->param('name');
		if(!\RegexHelper::is_en($name)){
			abort(404,'协议不存在');
		}
		list($title,$body) = \BaseHelper::GetXieYi($name);
		return view('',[
			'title' => $title,
			'body' => $body,
		]);
	}
	
	//修改资金密码
	public function pwd(){
		$request = Request::instance();
		$type = $request->param('type');
		$type = $type == 'pay' ? 'pay' : 'login';
		
		if($request->isPost()){
			$oldpwd = $request->param('oldpwd','','trim');
			$pwd1 = $request->param('pwd1','','trim');
			$pwd2 = $request->param('pwd2');
			if($oldpwd == ''){
				ajax('请输入原始密码');
			}
			if(strlen($pwd1)<6){
				ajax('密码长度不能少于6位');
			}
			if($pwd1 !== $pwd2){
				ajax('新密码输入不一致');
			}
			
			$type_req = $type == 'pay' ? 'paypwd' : 'loginpwd';
			$param = [
				'agentid' => AGENT_ID,
				'changetype' => $type_req,
				'oldpwd' => $oldpwd,
				'newpwd' => $pwd1,
			];
			
			$response = \ServerHelper::post('changepassword',$param);
			$data = $this->J($response);
			if(!isset($data['flag'])){
				ajax('修改失败');
			}
			if($data['flag'] == '0'){
				ajax($data['msg']);
			}
			ajax($data['msg'],true);
			
		}else{
			$typename = $type == 'pay' ? '资金密码' : '登陆密码';
			return view('',['type'=>$type,'typename'=>$typename]);
		}
	}

	//正式进入注册
	public function register(){

		$request = Request::instance();
		$agent_id = AGENT_ID;
		
		$inviterid = '';
		$invitelevels = []; //目标代理等级，其他代理等级不予显示
		if(Session::has('register_invitelevels')){
			$levels = Session::get('register_invitelevels');
			if(preg_match('/^[0-9a-zA-Z_]+(,[0-9a-zA-Z_]+)*$/',$levels)){
				$invitelevels = explode(',',$levels);
				$inviterid = Session::get('register_inviterid');
			}
		}
		
		$response = \ServerHelper::post('register_steps',[
			'agentid'=> $agent_id,
			'inviterid' => $inviterid
		]);
		$data = $this->J($response);
		
		if($data['data']['status'] == 0){
			//填写基本资料
			$data['data']['invitelevels'] = $invitelevels;
			$xieyilist = \BaseHelper::GetXieYiList();
			$data['data']['xieyilist'] = $xieyilist;
			return view('register_baseinfo',$data['data']);
		}else if($data['data']['status'] == 2){
			//付货款页面
			return view('register_select_huokuan_paytype',$data['data']);
		}else if($data['data']['status'] == 3){
			//等待货款审核
			return view('register_xxpay_huokuan_result',$data['data']); 
		}else if($data['data']['status'] == 4){
			//货款审核失败
			return view('register_xxpay_huokuan_result',$data['data']); 
		}else if($data['data']['status'] == 5){
			$data['data']['pagename'] = '缴纳保证金';
			//货款审核完成，未付保证金，显示付保证金页面
			return view('register_select_baozhengjin_paytype',$data['data']);
		}else if($data['data']['status'] == 6){
			//保证金待审核
			return view('register_xxpay_baozhengjin_result',$data['data']);
		}else if($data['data']['status'] == 7){
			//保证金审核失败
			return view('register_xxpay_baozhengjin_result',$data['data']);
		}else if($data['data']['status'] == 8){
			$this->redirect('/');
		}
	}
	
	//自动刷新审核状态用
	public function register_json_step(){
		$request = Request::instance();
		$agent_id = AGENT_ID;
		$inviterid = '';
		$invitelevels = [];
		if(Session::has('register_invitelevels')){
			$levels = Session::get('register_invitelevels');
			if(preg_match('/^[0-9a-zA-Z_]+(,[0-9a-zA-Z_]+)*$/',$levels)){
				$invitelevels = explode(',',$levels);
				$inviterid = Session::get('register_inviterid');
			}
		}
		$response = \ServerHelper::post('register_steps',[
			'agentid'=> $agent_id,
			'inviterid' => $inviterid
		]);
		$data = $this->J($response);
		ajax('success',true,$data['data']['status']);
	}
	
	//重新支付
	public function register_repay(){
		$request = Request::instance();
		$agent_id = AGENT_ID; //session('agent_id');
		$response = \ServerHelper::post('register_steps',['agentid'=>$agent_id]);
		$data = $this->J($response);
		if($data['data']['status'] > 4){
			return view('register_select_baozhengjin_paytype',$data['data']);
		}
		return view('register_select_huokuan_paytype',$data['data']);
	}
	
	//注册过程：状态1时，前端传过来代理基本信息，发送给后端保存
	public function baseinfo(){
		$request = Request::instance();
		$smscode = $request->param('smscode');
		$login_pwd1 = $request->param('login_pwd1');
		$login_pwd2 = $request->param('login_pwd2');
		if(strlen($login_pwd1) < 6 || strlen($login_pwd1) > 20){
			ajax('登陆密码长度错误');
		}
		$province = $request->param('province');
		$city = $request->param('city');
		$region = $request->param('region');
		//校验短信码
		$smscode_real = Cookie::get('smscode_register');
		if($smscode != $smscode_real){
			ajax('短信码错误');
		}
		$param = [
			'agentid' => AGENT_ID,
			'agentphonenum' => $request->param('phone'),
			'loginpassword' => $request->param('login_pwd1'),
			//'paypassword' => $request->param('trans_pwd'),
			'agentproduct' => '娜纹',
			'agentlevelid' => $request->param('agentlevelid'),
			'idnumber' => $request->param('idcard'),
			'realname' => $request->param('realname'),
			'sex' => $request->param('sex'),
			'area' => $province . ';' . $city . ';' . $region,
			'education' => $request->param('education'),
		];
		$response = \ServerHelper::post('register_baseinfo',$param);
		$data = $this->J($response);
		if(!empty($data['flag'])){
			Cookie::delete('smscode_register');
			ajax($data['msg'],true);
		}
		ajax($data['msg']);
	}
	
	
	//①线下支付
	public function register_xxpay(){
		
		$ordertype = Request::instance()->param('ordertype'); //订单类型(付哪一个步骤)
		$paytype = 1;//Request::instance()->param('paytype'); //支付类型
		
		//最小支付金额
		$minamount = Request::instance()->param('minamount',0,'floatval'); 
		//实际支付金额，不能小于最低支付金额
		$realamount = Request::instance()->param('realamount',0,'floatval'); 
		
		if($realamount < $minamount) $this->error('充值金额不能少于最低充值金额');
		if($ordertype  == '') $this->error('参数错误');
		if($paytype == '') $this->error('参数错误');
			
		if(Request::instance()->isPost()){
			$postdata = [
				'agentid' => AGENT_ID,
				'ordertype' => $ordertype,
				'paytype' => $paytype,
				'amount' => $realamount,
				'repaccounttype' => Request::instance()->param('repaccounttype'),
				'repaccount' => Request::instance()->param('repaccount'),
				'remark' => Request::instance()->param('remark'),
			];
			$reppicture = Request::instance()->param('reppicture');
			if($postdata['repaccounttype'] == '' || $postdata['repaccount'] == ''){
				$this->error('请选择收款人账户');
			}
			$arr = explode(',',$reppicture);
			if(count($arr) < 1 || substr($arr[0],0,4) != 'http'){
				$this->error('请上传打款凭证');
			}
			$postdata['reppicture'] = json_encode($arr);
			$response = \ServerHelper::post('register_xxpay_do',$postdata);
			$response = $this->J($response);
			if($response['flag']){
				$this->redirect('Member/register');
			}else{
				$this->error($response['msg']);
			}
			
		}else{
		
			$request = [
				'agentid' => AGENT_ID,
				'ordertype' => $ordertype,
			];
			
			$response = \ServerHelper::post('register_xxpay_show',$request);
			$response = $this->J($response);
			if($response['flag'] == 0){
				$this->error($response['msg']);
			}

			//选择数据
			$accountType = [];
			$accountTypeFull = [];
			if(isset($response['data']['repaccount']['wechat'])){
				$accountType[] = [
					'id'=>$response['data']['repaccount']['wechat']['accountid'],
					'value'=>$response['data']['repaccount']['wechat']['accountname'],
				];
				$accountTypeFull['wechat'] = [
					'id'=>$response['data']['repaccount']['wechat']['accountid'],
					'value'=>$response['data']['repaccount']['wechat']['accountname'],
				];
			}
			if(isset($response['data']['repaccount']['alipay'])){
				$accountType[] = [
					'id'=>$response['data']['repaccount']['alipay']['accountid'],
					'value'=>$response['data']['repaccount']['alipay']['accountname'],
				];
				$accountTypeFull['alipay'] = [
					'id'=>$response['data']['repaccount']['alipay']['accountid'],
					'value'=>$response['data']['repaccount']['alipay']['accountname'],
				];
			}
			if(isset($response['data']['repaccount']['bank'])){
				$accountType[] = [
					'id'=>$response['data']['repaccount']['bank']['accountid'],
					'value'=>$response['data']['repaccount']['bank']['accountname'],
				];
				$accountTypeFull['bank'] = [
					'id'=>$response['data']['repaccount']['bank']['accountid'],
					'value'=>$response['data']['repaccount']['bank']['accountname'],
				];
			}
			return view('',[
				'data' => $response['data'],
				'ordertype' => $ordertype,
				'paytype' => $paytype,
				'minamount' => $minamount,
				'realamount' => $realamount,
				'accounttype' => json_encode($accountType,JSON_UNESCAPED_UNICODE),
				'accounttypefull' => json_encode($accountTypeFull,JSON_UNESCAPED_UNICODE)
			]);
		}
	}
	
	//②微信支付
	public function wepay(){
		
		//现金余额、货款余额
		$orderid = Request::instance()->param('orderid');
		$ordertype = Request::instance()->param('ordertype'); //订单类型(付哪一个步骤)
		$paytype = Request::instance()->param('paytype'); //支付类型
		
		if($orderid == ''){
			$this->error('订单号错误');
		}
		if($ordertype  == ''){
			$this->error('参数错误');
		}
		if($paytype == ''){
			$this->error('参数错误');
		}
		
		//拉取支付信息
		$request = [
			'agentid' => AGENT_ID,
			'orderid' => $orderid,
			'ordertype' => $ordertype,
			'paytype' => $paytype,
		];
		$payinfo = \ServerHelper::post('wepay_show',$request);
		$payinfo = $this->J($payinfo);
		if($payinfo['flag'] != 1){ $this->error('支付发起失败'); }

		__log('orderid：'.$payinfo['data']['orderid'].'，payid：'.$payinfo['data']['payid'],'tmp' );
    
		$param = [
			'body' => $payinfo['data']['products'],
			'orderid' => $payinfo['data']['orderid'],
			'pay_no' => $payinfo['data']['payid'],
			'price' => intval($payinfo['data']['amount']), //价格(单位：分)
			'notify_url' => Request::instance()->domain() . url('Wepay/notify_url'),
		];
		    
		$url = url('Wepay/index') . '?' . http_build_query($param);
		
		$this->redirect($url);
    
	}
	
	
	private function getJson($url){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($ch);
		curl_close($ch);
		return json_decode($output, true);
	}

	
}


